import { MessageBox, Notification } from 'element-ui';
import { orderBy } from 'lodash';
import { listAuditGoodsApi, exportGoodsPriceApi, auditByQueryFormApi, auditByAuditGoodsIdsApi, updateAuditGoodsApi } from './api';
import { message, priceAuditCheckMessageBox } from '@/utils/util';
import { GoodsTableEditName } from '@/views/audit-price/constants';
import { errorHandler } from '@/utils';
import { ORDER_BY_FIELD_LIST, BATCHING_ADUIT_LIST, GOODS_STATUS_TYPES } from '@/constants';

export default {
  components: {},
  name: 'audit-price-edit-modal',
  props: {
    // 弹窗显隐
    visible: {
      type: Boolean,
      default: false,
    },
    // 上一页选中的 taskIds
    taskValueString: {
      type: Object,
      default: null,
    },
  },

  data() {
    return {
      labelWidth: '112px',

      goodsStatusTypes: GOODS_STATUS_TYPES,
      orderByFiledList: ORDER_BY_FIELD_LIST,

      formQuery: {}, // 查询条件
      channelRangeStart: undefined, // 建议原价毛利率最小值
      channelRangeEnd: undefined, // 建议原价毛利率最大值
      activityRangeStart: undefined, // 建议特价毛利率最小值
      activityRangeEnd: undefined, // 建议特价毛利率最大值

      querying: false, // 查询按钮loading

      data: [], // table 数据
      loading: false, // table loading
      total: 0,
      pageSize: 100,
      currentPage: 1,

      exporting: false, // 导出信息的按钮loading

      batchingAuditList: [...BATCHING_ADUIT_LIST], // 筛选字段列表
      allCheckedCols: [...BATCHING_ADUIT_LIST].filter(item => item.disabled).map(item => item.prop), // 选中的筛选字段
    };
  },
  directives: {
    focus: {
      inserted: function(el) {
        el.querySelector('input').focus();
      },
    },
  },
  methods: {
    // 弹窗打开-赋值上一页选中的 taskIds
    onOpen() {
      this.formQuery = { ...(this.taskValueString || {}) };
      this.data = []; // 解决弹窗关闭时 seenObj 报错问题
      this.onQuery();
    },
    // 点击【X】按钮
    onClose() {
      this.formQuery = {};
      this.channelRangeStart = undefined;
      this.channelRangeEnd = undefined;
      this.activityRangeStart = undefined;
      this.activityRangeEnd = undefined;

      this.querying = false;

      this.loading = false;
      this.total = 0;
      this.pageSize = 100;
      this.currentPage = 1;

      this.exporting = false;
      this.$emit('close');
    },

    // 导入价格信息
    onOpenImportModal() {
      this.$emit('onOpenImportModal');
    },
    // 导出价格信息
    async exportGoodsPrice() {
      try {
        this.exporting = true;
        const res = await exportGoodsPriceApi({ ...this.formQuery });
        if (!res) {
          Notification({ type: 'success', title: '提示', message: '导出成功！请打开下载任务页面获取数据' });
        }
        this.exporting = false;
      } catch (error) {
        this.exporting = false;
        errorHandler({ error });
      }
    },
    // 点击【全部审核】
    onAllAudit() {
      MessageBox.confirm('是否全部审核所有数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          if (this.data.length !== 0) {
            try {
              await auditByQueryFormApi(this.formQuery);
              message('提示', '操作成功', 'success');
              this.onQuery();
              priceAuditCheckMessageBox();
            } catch (e) {
              message('提示', '全部审核失败', 'error');
            }
          }
        })
        .catch(() => {
          message('提示', '已取消操作', 'warning');
        });
    },
    // 点击【批量审核】
    async onBatchAudit() {
      let selectdRow = this.$refs.goodsTable.selection.length === 0 ? null : this.$refs.goodsTable.selection;
      if (!selectdRow) {
        message('提示', '请选择商品记录', 'warning');
        return;
      }
      let auditGoodsIds = [];
      selectdRow.map(item => {
        auditGoodsIds.push(item.id);
      });

      try {
        await auditByAuditGoodsIdsApi(auditGoodsIds);
        message('提示', '操作成功', 'success');
        this.onQuery();
        priceAuditCheckMessageBox();
      } catch (e) {
        message('提示', '批量审核失败', 'error');
      }
    },

    // 列表分页查询
    async listData() {
      try {
        this.loading = true;
        this.querying = true;

        const result = await listAuditGoodsApi(this.formQuery, { pageSize: this.pageSize, pageNum: this.currentPage });
        // 清除选中项
        this.$refs.goodsTable && this.$refs.goodsTable.clearSelection();

        const { rows: data = [], total = 0 } = result || {};
        this.data = data.map(item => ({
          ...item,
          lastAdjustChannelPrice: item.channelPrice,
          seenObj: {
            auditChannelPrice: false,
            auditActivityPrice: false,
            auditLimitFrequency: false,
            auditLimitNum: false,
            auditActivityPriceLimit: false,
          },
        }));
        this.total = total;
      } catch (e) {
        message('错误', '获取数据失败', 'error');
      } finally {
        this.loading = false;
        this.querying = false;
      }
    },
    // 列表查询
    async onQuery(reset = true) {
      if (this.channelRangeStart !== undefined && this.channelRangeEnd !== undefined && this.channelRangeStart > this.channelRangeEnd) {
        message('提示', '查询条件【建议原价毛利率】最小值不得大于最大值', 'warning');
        return;
      }
      if (this.activityRangeStart !== undefined && this.activityRangeEnd !== undefined && this.activityRangeStart > this.activityRangeEnd) {
        message('提示', '查询条件【建议特价毛利率】最小值不得大于最大值', 'warning');
        return;
      }
      if ((this.formQuery.orderByFiled && !this.formQuery.orderBy) || (!this.formQuery.orderByFiled && this.formQuery.orderBy)) {
        message('提示', '查询条件【筛选数据】不完整', 'warning');
        return;
      }

      this.formQuery = {
        ...this.formQuery,
        newChannelPriceProfRange: {
          start: this.channelRangeStart,
          end: this.channelRangeEnd,
        },
        newActivityPriceProfRange: {
          start: this.activityRangeStart,
          end: this.activityRangeEnd,
        },
      };

      if (reset) {
        this.currentPage = 1;
        this.pageSize = 100;
      }

      await this.listData();
    },
    // 列表重置
    async reset() {
      this.formQuery = { ...(this.taskValueString || {}) };
      this.channelRangeStart = undefined;
      this.channelRangeEnd = undefined;
      this.activityRangeStart = undefined;
      this.activityRangeEnd = undefined;

      this.currentPage = 1;
      this.pageSize = 100;
      await this.listData();
    },
    onPageSizeChange(pageSize) {
      this.currentPage = 1;
      this.pageSize = pageSize;
      this.onQuery(false);
    },
    onPageNumChange(pageNum) {
      this.currentPage = pageNum;
      this.onQuery(false);
    },

    // 根据接口返回的status获取对应的文案展示
    formatStatusText(status) {
      if (!status) {
        return '';
      }

      let statusText = '';
      const filterList = GOODS_STATUS_TYPES.filter(item => item.id === status) || [];
      if (filterList.length > 0) {
        statusText = filterList[0].name || '';
      }
      return statusText;
    },

    // 全选
    handleCheckAllChange(val) {
      this.allCheckedCols = this.batchingAuditList.filter(item => (item.disabled ? true : !!val)).map(item => item.prop);
    },

    // 单元格点击
    cellClick(row, column) {
      switch (column.property) {
        case 'auditChannelPrice':
          row.seenObj.auditChannelPrice = true;
          break;
        case 'auditActivityPrice':
          row.seenObj.auditActivityPrice = true;
          break;
        case 'auditLimitFrequency':
          row.seenObj.auditLimitFrequency = true;
          break;
        case 'auditLimitNum':
          row.seenObj.auditLimitNum = true;
          break;
        case 'auditActivityPriceLimit':
          row.seenObj.auditActivityPriceLimit = true;
          break;
        default:
          break;
      }
    },
    // 单元格失焦
    tableColumnBlur(index, row, prop) {
      this.$nextTick(async () => {
        if (this.data.length === 0) {
          return;
        }

        if (this.data[index].seenObj[prop] === false) {
          return;
        }

        if (this.data[index][prop] === undefined || row[prop] === undefined) {
          message('提示', `第${index + 1}行【${GoodsTableEditName[prop]}】必填`, 'warning');
          return;
        }

        try {
          await updateAuditGoodsApi({
            id: this.data[index].id,
            [prop]: this.data[index][prop],
          });
          this.data.splice(index, 1, {
            ...this.data[index],
            seenObj: {
              ...this.data[index].seenObj,
              [prop]: false,
            },
          });
        } catch (error) {
          message('错误', error.message, 'error');
        }
      });
    },
    // 单元格 enter 键
    async tableColumnEnter(index, row, prop) {
      if (this.data.length === 0) {
        return;
      }

      if (this.data[index].seenObj[prop] === false) {
        return;
      }

      if (this.data[index][prop] === undefined || row[prop] === undefined) {
        message('提示', `第${index + 1}行【${GoodsTableEditName[prop]}】必填`, 'warning');
        return;
      }

      // e.target.blur();
      try {
        await updateAuditGoodsApi({
          id: this.data[index].id,
          [prop]: this.data[index][prop],
        });

        if (index === this.data.length - 1) {
          this.data.splice(index, 1, {
            ...this.data[index],
            seenObj: {
              ...this.data[index].seenObj,
              [prop]: false,
            },
          });
          return;
        }

        if (this.data[index + 1].status !== 'INIT' && this.data[index + 1].status !== 'REBUT') {
          this.data.splice(index, 1, {
            ...this.data[index],
            seenObj: {
              ...this.data[index].seenObj,
              [prop]: false,
            },
          });
          return;
        }

        this.data.splice(
          index,
          2,
          {
            ...this.data[index],
            seenObj: {
              ...this.data[index].seenObj,
              [prop]: false,
            },
          },
          {
            ...this.data[index + 1],
            seenObj: {
              ...this.data[index + 1].seenObj,
              [prop]: true,
            },
          },
        );
      } catch (error) {
        message('错误', error.message, 'error');
      }
    },
    // 编辑区域展示不同底色
    customStyle({ row, column }) {
      if (row.status === 'INIT' || row.status === 'REBUT') {
        if (column.property === 'auditChannelPrice' || column.property === 'auditActivityPrice') {
          return { backgroundColor: '#fcc997 !important' };
        }
        if (column.property === 'auditLimitFrequency' || column.property === 'auditLimitNum' || column.property === 'auditActivityPriceLimit') {
          return { backgroundColor: '#ddd !important' };
        }
      }
      return {};
    },
  },
  mounted() {},
  computed: {
    // 所有的table字段
    bindTableColumns() {
      return this.batchingAuditList;
    },
    // 是否全选【展示table的字段】
    checkAll() {
      return this.allCheckedCols.length === this.batchingAuditList.length;
    },
    // 选中的需要展示的table字段
    checkedTableColumns() {
      const obj = this.batchingAuditList.reduce((prev, curr, index) => {
        return { ...prev, [curr.prop]: { ...curr, index } };
      }, {});
      return orderBy(
        this.allCheckedCols.map(item => ({ ...obj[item] })),
        ['index'],
        ['asc'],
      );
    },
  },
};
